export default {
	data() {
		return {
			proList: [],
			priceDetail: {
				totalCount: 0, // 总件数
				totalMoney: 0, // 总原价
				saleDiscount: 0, // 商品优惠
				ticketDiscount: 0, // 优惠券优惠
				totalDiscount: 0, // 总优惠
				needMoney: 0, // 需支付
			},
			name: '',
			phone: '',
			region: [],
			regionStr: '',
			address: '',
			couponList: [],
			couponSelect: {}
		}
	},
	watch: {
		name: {
			handler(value) {
				this.name = value;
				uni.setStorageSync('booking_name', value);
			},
		},
		phone: {
			handler(value) {
				this.phone = value;
				uni.setStorageSync('booking_phone', value);
			},
		},
		region: {
			handler(value) {
				console.log("region", value);
				this.region = value;
				this.regionStr = value ? value.join(' ') : '';
				uni.setStorageSync('booking_region', this.region);
				uni.setStorageSync('booking_regionStr', this.regionStr);
			},
		},
		address: {
			handler(value) {
				this.address = value;
				uni.setStorageSync('booking_address', value);
			},
		},
	},
	async onLoad(options) {
		console.log("booking index onLoad: ", options);
		this.proList = JSON.parse(options.proList);
		console.log("this.proList: ", this.proList);
		if (this.proList && this.proList.length > 0) {
			// await this.getProductInfo();
			// await this.getCouponList();
			this.doPriceDetail();
		}
	},
	methods: {
		async getProductInfo() {
			for (let i = 0; i < this.proList.length; i++) {
				const detailRes = await this.$uniCloudCallFunction({
					name: 'xxf-product',
					action: "getProductDetail",
					data: {
						uid: this.$store.state.login.uid,
						id: this.proList[i].productId
					}
				});
				console.log("detailRes: ", detailRes);
				if (detailRes) {
					this.proList[i].productInfo = detailRes || {};
					for (let j = 0; j < detailRes.spu.length; j++) {
						if (detailRes.spu[j].spu_id === this.proList[i].spuId) {
							this.proList[i].spuInfo = detailRes.spu[j] || {};
						}
					}
				}
			}
			this.doPriceDetail();
		},
		doPriceDetail() {

			// totalCount: 0, // 总件数
			// totalMoney: 0, // 总原价
			// saleDiscount: 0, // 商品优惠
			// ticketDiscount: 0, // 优惠券优惠
			// totalDiscount: 0, // 总优惠
			// needMoney: 0, // 需支付

			let totalCount = 0,
				totalMoney = 0,
				saleDiscount = 0,
				ticketDiscount = 0,
				totalDiscount = 0,
				needMoney = 0;
			if (this.proList && this.proList.length > 0) {
				for (let i = 0; i < this.proList.length; i++) {
					const tmpItem = this.proList[i];
					totalCount = tmpItem.count + totalCount;
					totalMoney = tmpItem.count * tmpItem.spuInfo.price_original + totalMoney;
					saleDiscount = tmpItem.count * (tmpItem.spuInfo.price_original - tmpItem
						.spuInfo.price_sale) + saleDiscount;
				}
				// TODO
				ticketDiscount = 0;
				totalDiscount = saleDiscount + ticketDiscount;
				needMoney = totalMoney - totalDiscount;
				if (needMoney < 99) needMoney = needMoney + 8;
			}
			this.priceDetail = {
				totalCount,
				totalMoney,
				saleDiscount,
				ticketDiscount,
				totalDiscount,
				needMoney,
			}
		},
		async getCouponList() {
			const getRes = await this.$uniCloudCallFunction({
				name: "xxf-coupon",
				action: "getCouponList",
				data: {
					uid: this.$store.state.login.uid,
				}
			});
			console.log("getRes: ", getRes);
			if (getRes) {
				const allCouponList = getRes.list || [];
				this.couponList = allCouponList.filter(e => {
					if (e.is_used) {
						// 已使用
						return false;
					}
					if (e.is_expired) {
						// 已失效
						return false;
					}
					if (e.type === 1) {
						// 折扣券
						return true;
					} else if (e.type === 2) {
						// 满减券
						if (this.$store.state.login.role === 1) {
							if (e.couponInfo.usage_limit <= (this.priceDetail.totalMoney - this.priceDetail.activeDiscount)) {
								// 满减券 且达到满减条件
								return true;
							} else {
								return false;
							}
						} else if (this.$store.state.login.role === 2 || this.$store.state.login.role === 9) {
							if (e.couponInfo.usage_limit <= (this.priceDetail.totalMoney - this.priceDetail.vipDiscount - this
									.priceDetail.vip90Discount)) {
								// 满减券 且达到满减条件
								return true;
							} else {
								return false;
							}
						} else {
							return false;
						}
					}
				});
				console.log("this.couponList: ", this.couponList);
			}
		},
		chooseAddress() {
			const self = this;
			if (uni.chooseAddress) {
				uni.chooseAddress({
					success(res) {
						self.name = res.userName;
						self.phone = res.telNumber;
						self.region = [res.provinceName, res.cityName, res.countyName];
						self.regionStr = res.provinceName + ' ' + res.cityName + ' ' + res.countyName;
						self.address = res.detailInfo;
					},
					fail(res) {
						console.error('address error：', res);
						if (res.errMsg === 'chooseAddress:fail auth deny') {
							uni.showModal({
								title: "温馨提示",
								content: "您已拒绝授权将无法办理业务",
								showCancel: false,
								confirmText: "再次授权",
								confirmColor: "#1081FF",
								success(res) {
									if (res.confirm) {
										uni.openSetting({
											withSubscriptions: true,
											success(res) {
												self.chooseAddress()
											}
										})
									}
								}
							});
						}
					}
				});
			} else {
				console.warn('当前版本不支持!');
			}
		},
		countPlus(i) {
			this.proList[i].count++;
			this.doPriceDetail();
		},
		countMinus(i) {
			if (this.proList[i].count > 1) {
				this.proList[i].count--;
				this.doPriceDetail();
			}
		},
		async toBooking() {
			console.log('准备下单！');
			if (!this.name || !this.phone || !this.regionStr || !this.address) {
				await this.$utils.showToast(this, {
					message: '请完善收货信息！',
					mode: 2
				});
				return;
			}
			const putRes = await this.$uniCloudCallFunction({
				name: 'xxf-order',
				action: 'putOrder',
				data: {
					uid: this.$store.state.login.uid,
					totalCount: this.priceDetail.totalCount,
					totalMoney: this.priceDetail.totalMoney,
					activeDiscount: this.priceDetail.activeDiscount,
					vipDiscount: this.priceDetail.vipDiscount,
					ticketDiscount: this.priceDetail.ticketDiscount,
					totalDiscount: this.priceDetail.totalDiscount,
					needMoney: this.priceDetail.needMoney,
					proList: this.proList,
					receiveInfo: {
						name: this.name,
						phone: this.phone,
						region: this.region,
						regionStr: this.regionStr,
						address: this.address,
					}
				}
			});
			console.log('putRes: ', putRes);
			if (putRes) {
				// 删除购物车数据
				let cartIdArr = [];
				for (let i = 0; i < this.proList.length; i++) {
					const cartId = this.proList[i].cartId;
					if (!!cartId) cartIdArr.push(cartId);
				}
				if (cartIdArr.length > 0) {
					const delRes = await this.$uniCloudCallFunction({
						name: 'xxf-cart',
						action: 'deleteCart',
						data: {
							uid: this.$store.state.login.uid,
							cartIds: cartIdArr,
						}
					});
					console.log("delRes: ", delRes);
				}
				// 处理已使用优惠券
				if (this.couponSelect && this.couponSelect._id) {
					const useCouponRes = await this.$uniCloudCallFunction({
						name: 'xxf-coupon',
						action: 'useCoupon',
						data: {
							uid: this.$store.state.login.uid,
							id: this.couponSelect._id,
							coupon_id: this.couponSelect.coupon_id
						}
					});
					console.log("useCouponRes: ", useCouponRes);
				}
				// 订单支付
				await this.onPaying(putRes, () => {
					uni.redirectTo({
						url: "/pages/minePack/orders/index"
					})
				});
			}
		},
		openVip() {
			uni.navigateTo({
				url: "/pages/minePack/vip/index"
			})
		},
		selectTicket() {
			this.$refs.ticketRef.popupOpen({
				couponList: this.couponList
			});
		},
		popupChange(e) {
			this.popupShow = e.show;
		},
		confirmSelect(e) {
			this.couponSelect = e;
			this.doPriceDetail();
		},
		noSelect() {
			this.couponSelect = {};
			this.doPriceDetail();
		}
	}
}